package org.example.handler;

import org.example.common.ResponseData;
import org.springframework.http.HttpStatus;
import org.springframework.validation.method.MethodValidationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseData<String> handleExceptioin(Exception e){
        return ResponseData.fail("发生了异常："+e.getMessage());
    }

    @ExceptionHandler(MethodValidationException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseData<String> handleValidationExcertion(Exception ex){
        StringBuilder errors = new StringBuilder();
        ex.getBindingResult().getFieldErrors().forEach(error ->
                error.append(error.getDfaultMessage()).append(";"));
        return ResponseData.fail(errors.toString());
    }

}


